//
//  HMSetInformationViewController.m
//  HowToDo
//
//  Created by 李贺 on 2017/1/6.
//  Copyright © 2017年 KY. All rights reserved.
//

#import "HMSetInformationViewController.h"
#import "HeaderImageCell.h"
//#import <AFHTTPRequestOperationManager.h>
#import "BaseInformationTableViewCell.h"
#import "Masonry.h"

@interface HMSetInformationViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIGestureRecognizerDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
///头像
@property (nonatomic, strong) UIImageView *headIcon;
///灰色覆盖面
@property (nonatomic, strong) UIView *coverView;
///信息数组
@property (nonatomic, strong) NSArray *informationArray;
///pickerView
@property (nonatomic, strong) UIPickerView *pickerView;
///出生信息
@property (nonatomic, strong) UITextField *birthdayTextField;
///学历
@property (nonatomic, strong) UITextField *EducationTextField;
///行业
@property (nonatomic, strong) UITextField *vocationKindTextField;
///职业
@property (nonatomic, strong) UITextField *vocationTextField;
///哪个cell
@property (nonatomic, strong) NSIndexPath *selectedIndexpath;
///性别选择
@property (nonatomic, strong) UITextField *sexTextField;

@property (nonatomic, strong) UITextField *nameTextField;

@end

@implementation HMSetInformationViewController

{
    UIImagePickerController *pickerController;
//    AFHTTPRequestOperationManager *manager;
}

+ (instancetype)sharedInfomationVC{
    static id _instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[HMSetInformationViewController alloc]init];
    });
    return _instance;
}



// 懒加载
- (NSArray *)informationArray {
    if (!_informationArray) {
        _informationArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"setInformation.plist" ofType:nil]];
    }
    return _informationArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"编辑资料";
    self.navigationController.navigationBarHidden = NO;
    
    //初始化pickController
    [self createData];
    
    UITableView * tab = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    
    [self.view addSubview:tab];
    
    //tabbleView代理
    tab.dataSource = self;
    tab.delegate = self;
    
    // 预估行高
    tab.estimatedRowHeight = 100;
    
    // 3.用class来注册cell
    [tab registerClass:[HeaderImageCell class] forCellReuseIdentifier:@"HeaderImageCell_ID"];
    
    [tab registerClass:[BaseInformationTableViewCell class] forCellReuseIdentifier:@"BaseInformationTableViewCell_ID"];
    
    // 清空分割线的内边距
    tab.separatorInset = UIEdgeInsetsZero;
    
}



#pragma mark -tabbleView代理-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0){
        return 1;
    }
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        HeaderImageCell * tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"HeaderImageCell_ID"];
        tableViewCell.headIcon.backgroundColor = [UIColor lightGrayColor];
        NSString * path = [self getPhotoFilePath];
        tableViewCell.headIcon.image = [UIImage imageWithContentsOfFile:path];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
        tableViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
        tableViewCell.headIcon.userInteractionEnabled = YES;
        [tableViewCell.headIcon addGestureRecognizer:tapGesture];
        self.headIcon = tableViewCell.headIcon;
        return tableViewCell;
    }
    BaseInformationTableViewCell * tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"BaseInformationTableViewCell_ID"];
    if(indexPath.section == 1 && indexPath.row == 0){
        tableViewCell.nameLable.text = @"  昵称:";
        self.nameTextField = tableViewCell.informationTextField;
        
        NSString *str2 = [self getPhotoFilePathWithNSString:@"name"];
        NSString *str = [NSString stringWithContentsOfFile:str2 encoding:NSUTF8StringEncoding error:nil];
        tableViewCell.informationTextField.text = str;
    }
    else{
        tableViewCell.informationTextField.userInteractionEnabled = NO;

        if(indexPath.section == 1 && indexPath.row == 1){
            tableViewCell.nameLable.text = @"  性别:";
            NSString *str2 = [self getPhotoFilePathWithNSString:@"man"];
            NSString *str = [NSString stringWithContentsOfFile:str2 encoding:NSUTF8StringEncoding error:nil];
            tableViewCell.informationTextField.text = str;
            self.sexTextField= tableViewCell.informationTextField;
        } else if(indexPath.section == 1 && indexPath.row == 2){
            tableViewCell.nameLable.text = @"  出生年份:";
            self.birthdayTextField = tableViewCell.informationTextField;
            NSString *str2 = [self getPhotoFilePathWithNSString:@"birthday"];
            NSString *str = [NSString stringWithContentsOfFile:str2 encoding:NSUTF8StringEncoding error:nil];
            tableViewCell.informationTextField.text = str;
        } else{
            if(indexPath.row == 0){
                tableViewCell.nameLable.text = @"  学历:";
                self.EducationTextField = tableViewCell.informationTextField;
                NSString *str2 = [self getPhotoFilePathWithNSString:@"xueli"];
                NSString *str = [NSString stringWithContentsOfFile:str2 encoding:NSUTF8StringEncoding error:nil];
                tableViewCell.informationTextField.text = str;
            } else if(indexPath.row == 1){
                tableViewCell.nameLable.text = @"  行业:";
                self.vocationKindTextField = tableViewCell.informationTextField;
                NSString *str2 = [self getPhotoFilePathWithNSString:@"hangye"];
                NSString *str = [NSString stringWithContentsOfFile:str2 encoding:NSUTF8StringEncoding error:nil];
                tableViewCell.informationTextField.text = str;
            } else{
                tableViewCell.nameLable.text = @"  职业:";
                self.vocationTextField = tableViewCell.informationTextField;
                NSString *str2 = [self getPhotoFilePathWithNSString:@"zhiye"];
                NSString *str = [NSString stringWithContentsOfFile:str2 encoding:NSUTF8StringEncoding error:nil];
                tableViewCell.informationTextField.text = str;
            }
        }
    }
    return tableViewCell;
}


///返回每一行的具体行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0){
        return 200;
    }
    return 54;
}

///取消选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //退出键盘
    [self.view endEditing:YES];
    if(self.recallNameStringBlock){
        self.recallNameStringBlock(self.nameTextField.text);
    }
    NSString *newFielPath = [self getPhotoFilePathWithNSString:@"name"];
    
    [self.nameTextField.text writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1 && indexPath.row == 2){
        [self setInformation];
        self.selectedIndexpath = indexPath;
    }
    if(indexPath.section == 2){
        [self setInformation];
        self.selectedIndexpath = indexPath;
    }
    if(indexPath.section == 1 && indexPath.row == 1){
        [self sexSelection];
    }
}

///性别选择
- (void)sexSelection{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle: nil                                                                             message: nil                                                                       preferredStyle:UIAlertControllerStyleActionSheet];
    //添加Button
    [alertController addAction: [UIAlertAction actionWithTitle: @"男" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.sexTextField.text = @"男";
        
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"man"];
        
        [self.sexTextField.text writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"女" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        self.sexTextField.text = @"女";
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"man"];
        
        [self.sexTextField.text writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"保密" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        self.sexTextField.text = @"保密";
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"man"];
        
        [self.sexTextField.text writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated:YES completion:nil];
    
}

///其他信息存储到本地的路径
- (NSString *)getPhotoFilePathWithNSString:(NSString *)str{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    //指定新建文件夹路径
    NSString *filePath = [documentPath stringByAppendingPathComponent:str];
    return filePath;
}


//cell点击响应事件
- (void)setInformation{
    self.coverView = [[UIView alloc] initWithFrame:self.view.bounds];
    _coverView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.6];
    [self.view addSubview:_coverView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeCellClick)];
    [_coverView addGestureRecognizer:tapGesture];
    
    UIPickerView * pickerView = [[UIPickerView alloc] init];
    
    [pickerView setBackgroundColor:[UIColor whiteColor]];
    [self.coverView addSubview:pickerView];
    
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.coverView);
        make.height.offset(250);
    }];
    
    self.pickerView = pickerView;
    
    // pickerView设置数据源
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
}

//取消cell点击事件
- (void)closeCellClick{
    [UIView animateWithDuration:0.25 animations:^{
        self.coverView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.coverView removeFromSuperview];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return 0.0001;
    }
    return 10;
}



#pragma mark - 头像设置
///轻击手势触发方法
-(void)tapGesture:(UITapGestureRecognizer *)sender
{
    [self makePhotoBombBox];
}

///调用相机弹框
- (void)makePhotoBombBox{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"选择头像"                                                                             message: nil                                                                     preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction: [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            //            NSLog(@"支持相机");
            [self makePhoto];
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"提示"                                                                             message: @"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！"                                                                       preferredStyle:UIAlertControllerStyleAlert];
            
            [alertController addAction: [UIAlertAction actionWithTitle: @"我知道了" style: UIAlertActionStyleDefault handler:nil]];
            [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
            [self presentViewController: alertController animated: YES completion: nil];
        }
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"相册" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            //            NSLog(@"支持相册");
            [self choosePicture];
        }
        else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"提示"                                                                             message: @"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！"                                                                       preferredStyle:UIAlertControllerStyleAlert];
            
            [alertController addAction: [UIAlertAction actionWithTitle: @"我知道了" style: UIAlertActionStyleDefault handler:nil]];
            [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
            [self presentViewController: alertController animated: YES completion: nil];
        }
        
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"图库" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
        {
            //            NSLog(@"支持图库");
            [self pictureLibrary];
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"提示"                                                                             message: @"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！"                                                                       preferredStyle:UIAlertControllerStyleAlert];
            
            [alertController addAction: [UIAlertAction actionWithTitle: @"我知道了" style: UIAlertActionStyleDefault handler:nil]];
            [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
            [self presentViewController: alertController animated: YES completion: nil];
        }
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated:YES completion:nil];
}


- (void)createData
{
    //初始化pickerController
    pickerController = [[UIImagePickerController alloc]init];
    pickerController.view.backgroundColor = [UIColor orangeColor];
    pickerController.delegate = self;
    pickerController.allowsEditing = YES;
}

//跳转到imagePicker里
- (void)makePhoto
{
    pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:pickerController animated:YES completion:nil];
}

//跳转到相册
- (void)choosePicture
{
    pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:pickerController animated:YES completion:nil];
}

//跳转图库
- (void)pictureLibrary
{
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:pickerController animated:YES completion:nil];
}

//用户取消退出picker时候调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [pickerController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//用户选中图片之后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *userImage = [self fixOrientation:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
    userImage = [self scaleImage:userImage toScale:0.3];
    [pickerController dismissViewControllerAnimated:YES completion:^{
        
    }];
    [self.headIcon setImage:userImage];
    self.headIcon.contentMode = UIViewContentModeScaleAspectFill;
    self.headIcon.clipsToBounds = YES;
    if(self.recallImageBlock){
        self.recallImageBlock(userImage);
    }
    [self saveImage:userImage name:nil];
    
#warning   照片上传  有关网络的  全都注释掉了
//    [self upDateHeadIcon:userImage];
}

/*
- (void)upDateHeadIcon:(UIImage *)photo
{
    //使用NSData数据流传图片
    NSString *imageURl = @"";
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"text/html"];
    [manager POST:imageURl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:UIImageJPEGRepresentation(photo, 1.0) name:@"text" fileName:@"test.jpg" mimeType:@"image/jpg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}*/

///照片存储到本地的路径
- (NSString *)getPhotoFilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    //指定新建文件夹路径
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"PhotoFile.JPEG"];
    return filePath;
}

//保存照片到沙盒路径(保存)
- (void)saveImage:(UIImage *)image name:(NSString *)iconName
{
    NSString *filePath = [self getPhotoFilePath];
    [UIImagePNGRepresentation(image)writeToFile: filePath  atomically:YES];
}

//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}



#pragma mark  -pickerView代理-
// 返回多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// 返回多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if(self.selectedIndexpath.section == 1){
        NSArray *array = self.informationArray[0];
        return array.count;
    }
    else if(self.selectedIndexpath.section == 2 && self.selectedIndexpath.row == 0){
        NSArray *array = self.informationArray[1];
        return array.count;
    }
    else if(self.selectedIndexpath.section == 2 && self.selectedIndexpath.row == 1){
        NSArray *array = self.informationArray[2];
        return array.count;
    }
    NSArray *array = self.informationArray[3];
    return array.count;
    
}

// 每行的内容
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if(self.selectedIndexpath.section == 1){
        NSArray *array = self.informationArray[0];
        return array[row];
    }
    else if(self.selectedIndexpath.section == 2 && self.selectedIndexpath.row == 0){
        NSArray *array = self.informationArray[1];
        return array[row];
    }
    else if(self.selectedIndexpath.section == 2 && self.selectedIndexpath.row == 1){
        NSArray *array = self.informationArray[2];
        return array[row];
    }
    NSArray *array = self.informationArray[3];
    return array[row];
    
}

// 监听手动滚动,滚动停止后调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    if(self.selectedIndexpath.section == 1){
        NSArray * array = self.informationArray[0];
        NSString * str = array[row];
        self.birthdayTextField.text = str;
        
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"birthday"];

        [str writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    else if(self.selectedIndexpath.section == 2 && self.selectedIndexpath.row == 0){
        NSArray * array = self.informationArray[1];
        NSString * str = array[row];
        self.EducationTextField.text = str;
        
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"xueli"];

        [str writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    else if(self.selectedIndexpath.section == 2 && self.selectedIndexpath.row == 1){
        NSArray * array = self.informationArray[2];
        NSString * str = array[row];
        self.vocationKindTextField.text = str;
        
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"hangye"];

        [str writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    } else{
        NSArray *array = self.informationArray[3];
        NSString * str = array[row];
        self.vocationTextField.text = str;
        NSString *newFielPath = [self getPhotoFilePathWithNSString:@"zhiye"];

        [str writeToFile:newFielPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
